package com.qf.fmall2302.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;

@Component
@ServerEndpoint("/webSocket/{orderid}")
public class OrderWebSocketServer {

    public static HashMap<String,Session> sessionMap
            = new HashMap<String,Session>();

    public static void pushMsg(String orderid, String msg) throws IOException {
        Session session = sessionMap.get(orderid);
        session.getBasicRemote().sendText(msg);
    }

    @OnOpen
    public void onOpen(@PathParam("orderid") String orderid,
                       Session session){

        System.out.println("接收到浏览器的连接请求，orderid="+orderid);
        // 如何保存与该浏览器建立的 session对象呢 ？
        sessionMap.put(orderid,session);

    }

    @OnClose
    public void onClose(@PathParam("orderid") String orderid,
                        Session session) throws IOException {
        // 移除 map中对应的session对象
        sessionMap.remove(orderid);
        session.close();
    }

}
